package com.file.module.service;

import com.file.module.entity.File;
import com.file.module.mapper.FileMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class FileService {

    @Resource
    private FileMapper fileMapper;

    public List<File> getAllImage(){
        return fileMapper.getAllImage();
    }

    public File getById(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        }
        return fileMapper.getById(id);
    }

    public File extractById(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        }
        return fileMapper.extractById(id);
    }

    public int insert(File file) {
        return fileMapper.insert(file);
    }

    public int update(File file) {
        return fileMapper.update(file);
    }

    public int delete(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        } else {
            if (getById(id) == null) {
                throw new RuntimeException("File not found");
            }
        }
        int timeStamp = (int) (System.currentTimeMillis() / 1000);
        return fileMapper.delete(id, timeStamp);
    }

    public Long edit(
            Integer type,
            String url,
            Long id
    ) throws RuntimeException {
        int timeStamp = (int) (System.currentTimeMillis() / 1000);
        File file = new File();

        file.setType(type);
        file.setUrl(url);

        file.setIsDeleted(0);

        if (id == null) {
            file.setCreateTime(timeStamp);
            insert(file);
        } else {
            file.setId(id);
            if (getById(id) == null) {
                throw new RuntimeException("File not found");
            } else {
                update(file);
            }
        }
        return file.getId();
    }
}